package snail.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import snail.data.UserDAO;
import snail.model.User;
import snail.hibernate.util.*;
import snail.misc.PreparedModelAndView;
import snail.validators.EditUserValidator;

public class EditUserController extends SimpleFormController {

    @Override
    protected void doSubmitAction(Object command) throws Exception {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(request.getSession().getAttribute("user") == null)
        {
            return new UserController().login(request, response, "edit");
        }

        ModelAndView mv =  super.handleRequestInternal(request, response);
        ModelAndView mav = new PreparedModelAndView(request);
        if(mv != null){
            mv.addAllObjects(mav.getModelMap());
            mv.setViewName("user/edit");
        }
        return mv;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {

        return (User) request.getSession().getAttribute("user");
    }

    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            org.springframework.validation.BindException errors) throws Exception {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        this.setValidator(new EditUserValidator());

        User userSession = (User)request.getSession().getAttribute("user");
        User userFromForm = (User) command;
        String firstName = userFromForm.getFirstName();
        String lastName = userFromForm.getLastName();
        String address = userFromForm.getAddress();
        String postAddress = userFromForm.getPostAddress();
        request.getSession().setAttribute("user", userFromForm);

        User user = new UserDAO().getByEmail(userSession.getEmail());
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setAddress(address);
        user.setPostAddress(postAddress);
        
        session.getTransaction().commit();
        response.sendRedirect("profile");
        return null;





    }
}